package com.m3839.sdk.login.model;

import static com.m3839.sdk.common.core.Constant.HYKB_EVENT_LOGIN_SUCCESS;

import com.m3839.sdk.common.GlobalManager;
import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.SdkConfiguration;
import com.m3839.sdk.common.env.EnvConfig;
import com.m3839.sdk.common.env2.ApiManager;
import com.m3839.sdk.common.event.SubjectBus;
import com.m3839.sdk.common.http.IHttpManager;
import com.m3839.sdk.common.http.listener.SimpleHttpRequestListener;
import com.m3839.sdk.common.util.LogUtils;
import com.m3839.sdk.login.bean.InternalUser;
import com.m3839.sdk.login.bean.InternalTip;
import com.m3839.sdk.login.model.api.ILoginModel;
import com.m3839.sdk.login.utils.UserUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * @author ChenBaoyang
 * @description: LoginApiModel
 * @date 2021/12/8 10:22
 */
public class LoginApiModel implements ILoginModel {

    private static final String TAG = "LoginApiModel";

    /** 登录校验接口 */
    private static final String AUTH_PATH = "user/grant";

    /** 获取登录对外游戏登录校验的accessToken的接口 */
    private static final String ACCESS_TOKEN_PATH = "kuaibao/android/devsdk.php";


    /** SDK登录校验url */
    private static final String AUTH_BASE_URL = ApiManager.getInstance().buildYuanChuangUrl(AUTH_PATH);

    /** SDK登录获取accessToken的url */
    private static final String ACCESS_TOKEN_BASE_URL = ApiManager.getInstance().buildKuaiBaoUrl(ACCESS_TOKEN_PATH);


    @Override
    public void authCheck(InternalUser user) {
        Map<String, Object> param = ApiManager.getInstance().getCommonParam(user.getUserId(), AUTH_PATH);
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        EnvConfig config = ApiManager.getInstance().getYuanChuangApiEnvConfig();

        httpManager.requestPost(AUTH_BASE_URL, param,
                ApiManager.getInstance().getAuthHeaders(config, UserUtils.getState(user)),
                new SimpleHttpRequestListener() {

                    @Override
                    public void onResult(String response) throws JSONException {
                        parseUserJson(response, user);
                    }

                    @Override
                    public void onError(ApiError apiError) {
                        LogUtils.e(TAG, apiError.toString());
                    }

                });
    }

    /**
     * 解析用户校验的结果
     *
     * @param response
     * @throws JSONException
     */
    private void parseUserJson(String response, final InternalUser user)
            throws JSONException {
        JSONObject data = new JSONObject(response);

        final int code = data.optInt(Constant.HYKB_KEY_RESPONSE_CODE);
        String msg = data.optString(Constant.HYKB_KEY_RESPONSE_MSG);

        JSONObject dataJson = data.optJSONObject(Constant.HYKB_KEY_RESPONSE_DATA);
        switch (code) {
            case Constant.HYKB_CODE_SUCCESS:
                SdkConfiguration.setFcmStatus(dataJson.optInt(Constant.HYKB_KEY_RESPONSE_FCM));
                try {
                    loadAccessToken(user);
                } catch (JSONException e) {
                    SubjectBus.get().postValue(HYKB_EVENT_LOGIN_SUCCESS, null);
                }
                break;

            case Constant.HYKB_CODE_USER_BANNED:
                //显示账号被封禁的对话框
                String tipContent = dataJson.optString(Constant.HYKB_KEY_RESPONSE_CONTENT);
                final InternalTip tip = InternalTip.getSwitchAccountTip(tipContent);
                SubjectBus.get().postValue(Constant.HYKB_EVENT_LOGIN_BANNED, tip);
                break;

            case Constant.HYKB_CODE_USER_ROBBED:
                //code : 2003 表示用户被抢登
                final InternalTip tip2 = InternalTip.getLoginAgainTip(msg);
                SubjectBus.get().postValue(Constant.HYKB_EVENT_LOGIN_BANNED, tip2);
                break;
            default:
                //默认都是校验失败
                ApiError error = new ApiError(code, msg);
                SubjectBus.get().postValue(Constant.HYKB_EVENT_LOGIN_FAILED, error);
                break;
        }
    }

    /**
     * 获取请求需要的参数，json形式
     *
     * @throws JSONException
     */
    private JSONObject getJsonParam(String appId, InternalUser user) throws JSONException {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("c", "authgame");
        jsonParam.put("a", "getAccessToken");
        jsonParam.put("v", "1546");
        jsonParam.put("app_id", appId);
        jsonParam.put("uid", user.getUserId());
        jsonParam.put("type", user.getType());
        jsonParam.put("user_token", user.getToken());
        return jsonParam;
    }

    /**
     * 获取快爆用户心校验码
     */
    public void loadAccessToken(final InternalUser user) throws JSONException {
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        JSONObject jsonParam = getJsonParam(SdkConfiguration.getGameId(), user);

        httpManager.requestPost(ACCESS_TOKEN_BASE_URL, jsonParam,
                new SimpleHttpRequestListener() {

                    @Override
                    public void onResult(String response) throws JSONException {
                        JSONObject data = new JSONObject(response);

                        final int code = data.optInt(Constant.HYKB_KEY_RESPONSE_CODE);
                        JSONObject resultJson = data.optJSONObject(Constant.HYKB_KEY_RESPONSE_RESULT);
                        String accessToken = null;
                        if (code == 100) {
                            accessToken = resultJson.optString(Constant.HYKB_KEY_RESPONSE_ACCESS_TOKEN);
                            LogUtils.flog("accessToken = " + accessToken);
                        }
                        SubjectBus.get().postValue(HYKB_EVENT_LOGIN_SUCCESS, accessToken);
                    }

                    @Override
                    public void onError(ApiError apiError) {
                        SubjectBus.get().postValue(HYKB_EVENT_LOGIN_SUCCESS, null);
                    }
                });

    }
}
